// Ionic Starter App

// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.services' is found in services.js
// 'starter.controllers' is found in controllers.js
var starter = angular.module('starter',
        ['ionic','oc.lazyLoad','angularFileUpload', 'starter.controllers', 'starter.services'])

    //.constant('ApiEndpoint', {
    //
    //  /*url: 'http://192.168.0.104:8080/env/'*/  /*家*/
    //  /*url: 'http://10.0.1.67:8080/env/'*/ /*融科本机*/
    //  /*url: 'http://58.52.161.94:8080/env/'*/  /*正式*/
    //        //url: 'http://10.100.235.171/gjad/' /*公交*/
    //  //url: 'http://10.100.235.163:8060/gjad_web/less/' /*公交*/
    //        url : "../../"
    //  /*url: 'http://10.0.1.202:10060/env/'*/ /*融科202*/
    //  /*url: 'http://10.174.113.98:8080/env/'*/ /*咸宁vpn环境下的本机*/
    //        //url: 'http://10.100.235.171/gjad/less/'
    //
    //    })
    .run(function ($ionicPlatform) {
        $ionicPlatform.ready(function () {
            // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
            // for form inputs)
            if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
                cordova.plugins.Keyboard.disableScroll(true);

            }
            if (window.StatusBar) {
                // org.apache.cordova.statusbar required
                StatusBar.styleDefault();
            }

            //程序启动后退出欢迎界面
            //navigator.splashscreen.hide();

            //锁定屏幕方向
            //screen.lockOrientation('portrait');


            //app开启状态：收到通知
            document.addEventListener("jpush.receiveNotification", function (event) {
                var alertContent
                if (device.platform == "Android") {
                    alertContent = window.plugins.jPushPlugin.receiveNotification.alert;
                } else {
                    alertContent = event.aps.alert;
                }
                //alert("receiveNotification:"+alertContent);
            }, false);

            //app后台状态：点击通知，打开app
            document.addEventListener("jpush.openNotification", function (event) {

                var alertContent
                if (device.platform == "Android") {
                    alertContent = window.plugins.jPushPlugin.openNotification.alert;
                } else {
                    alertContent = event.aps.alert;
                }
                //alert("openNotification:"+alertContent);
            }, false);


        });
    })

    .factory('settings', ['$rootScope', 'Page','ApiEndpoint', function($rootScope, Page,ApiEndpoint) {
    	var settings = {};
    	Page.ajaxPostQuiet(ApiEndpoint.settingUrl, null, function(resp) {
	        $rootScope.nginxPath = "../../" + resp.data.nginxPath;
            //$rootScope.nginxPath =  resp.data.nginxPath;
    	});
    	$rootScope.settings = settings;
        return settings;
    }])

    .factory('HttpInterceptor',['localStore', function (localStore) {
        // ---
        // PRVIATE METHODS.
        // ---
        // I serialize the given Object into a key-value pair string. This
        // method expects an object and will default to the toString() method.
        // --
        // NOTE: This is an atered version of the jQuery.param() method which
        // will serialize a data collection for Form posting.
        // --
        // https://github.com/jquery/jquery/blob/master/src/serialize.js#L45
        function serializeData(data) {
            // If this is not an object, defer to native stringification.
            if (!angular.isObject(data)) {
                return ((data == null) ? "" : data.toString());
            }
            var buffer = [];
            // Serialize each key in the object.
            for (var name in data) {
                if (!data.hasOwnProperty(name)) {
                    continue;
                }
                var value = data[name];
                if (angular.isObject(value)) {
                    value = angular.toJson(value);
                }
                buffer.push(encodeURIComponent(name) + "=" + encodeURIComponent((value == null) ? "" : value));
            }
            // Serialize the buffer and clean it up for transportation.
            var source = buffer.join("&").replace(/%20/g, "+");
            return (source);
        }

        return {
            request: function (config) {
                if (config.data && angular.isObject(config.data)) {
                    if (config.method === 'POST') {
                        var token = localStore.get("token");
                        var userId = localStore.get("userId");
                        config.data["access_token"] = token;
                        config.data["user_id"] = userId;
                        config.data = serializeData(config.data);
                    } else if (config.method === 'GET') {
                        config.url += (config.url.indexOf('?') > 0 ? '&' : '?') + serializeData(config.data);
                    }
                }

                return config;
            }
        };
    }])

    .factory('AuthInterceptor', ["$q","$window", "$rootScope","localStore", function ($q,$window,$rootScope,localStore) {
        return {
            request: function (config) {
                var token = localStore.get("token");
                var userId = localStore.get("userId");
                if(token != undefined && token != "" && userId != undefined && userId != "") {
                } else {
                    //if(window.js != undefined && window.js.mobileAlert != undefined) {
                    //    window.js.mobileAlert("提示","登录超时",true);
                    //} else {
                    //    window.webkit.messageHandlers.mobileAlert.postMessage({title:'提示',content:'登录超时!' + token + ',' + userId,action:true})
                    //}
                }
                return config;
            },
            responseError: function (response) {

                if(response.data.error == "invalid_token") {
                    //if(window.js != undefined && window.js.mobileAlert != undefined) {
                    //    window.js.mobileAlert("提示","登录超时",true);
                    //} else {
                    //    window.webkit.messageHandlers.mobileAlert.postMessage({title:'提示',content:'登录超时!',action:false})
                    //}
                }

                return $q.reject(response);
            }
        };
    }])

    .config(['$ocLazyLoadProvider', function($ocLazyLoadProvider) {
        $ocLazyLoadProvider.config({
            // global configs go here
        });
    }])

    .config(function ($stateProvider, $urlRouterProvider, $httpProvider,$ionicConfigProvider) {
        $httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        $httpProvider.interceptors.push('HttpInterceptor');
        $httpProvider.interceptors.push('AuthInterceptor');
        $ionicConfigProvider.views.swipeBackEnabled(false);
        $ionicConfigProvider.views.transition('none');
        // Ionic uses AngularUI Router which uses the concept of states
        // Learn more here: https://github.com/angular-ui/ui-router
        // Set up the various states which the app can be in.
        // Each state's controller can be found in controllers.js
        $stateProvider

            // setup an abstract state for the tabs directive

            // Each tab has its own nav history stack:

            //.state('doc', {
            //    url: '/doc',
            //    templateUrl: 'templates/doc.html',
            //    controller: 'docCtrl'
            //})
            //.state('meeting', {
            //    url: '/meeting',
            //    templateUrl: 'templates/meeting.html',
            //    controller: 'meetingCtrl'
            //})
            //.state('leave', {
            //    url: '/leave',
            //    templateUrl: 'templates/leave.html',
            //    controller: 'leaveCtrl'
            //})
            //.state('assets', {
            //    url: '/assets',
            //    templateUrl: 'templates/assets.html',
            //    controller: 'assetsCtrl'
            //})
            //.state('waitdo', {
            //    url: '/waitdo',
            //    templateUrl: 'templates/waitdo.html',
            //    controller: 'waitdoCtrl'
            //})
            //.state('alreadydo', {
            //    url: '/alreadydo',
            //    templateUrl: 'templates/alreadydo.html',
            //    controller: 'alreadydoCtrl'
            //})
            //.state('approve', {
            //    url: '/approve',
            //    templateUrl: 'templates/approve.html',
            //    controller: 'approveCtrl'
            //})
            //.state('leaveApply', {
            //    url: '/leaveApply',
            //    templateUrl: 'templates/leave_apply.html',
            //    controller: 'leaveApplyCtrl'
            //})
            //.state('myStarted', {
            //    url: '/myStarted',
            //    templateUrl: 'templates/myStarted.html',
            //    controller: 'myStartedCtrl'
            //})
            //.state('cloudSpace', {
            //    url: '/cloudSpace',
            //    templateUrl: 'templates/cloudSpace.html',
            //    controller: 'cloudSpaceCtrl'
            //})
            //.state('myInfo', {
            //    url: '/myInfo',
            //    templateUrl: 'templates/myInfo.html',
            //    controller: 'myInfoCtrl'
            //})
            //.state('signIn', {
            //    url: '/signIn',
            //    templateUrl: 'templates/signIn.html',
            //    controller: 'signInCtrl'
            //})
            .state('bus_check', {
                url: '/bus_check',
                data: {pageTitle: '车辆检查'},
                templateUrl: 'templates/bus_check.html',
                controller: 'busCheckTaskController',
                cache : false,
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/busCheckTaskController.js',
                                'plugins/iosselect/iosSelect.css',
                                'plugins/iosselect/iscroll.js',
                                'plugins/iosselect/iosSelect.js',
                                'plugins/iosselect/iosMultiSelect.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })

            .state('stop_check', {
                url: '/stop_check',
                data: {pageTitle: '站点检查'},
                templateUrl: 'templates/stop_check.html',
                controller: 'stopCheckTaskController',
                cache : false,
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/stopCheckTaskController.js',
                                'plugins/iosselect/iosSelect.css',
                                'plugins/iosselect/iscroll.js',
                                'plugins/iosselect/iosSelect.js',
                                'plugins/iosselect/iosMultiSelect.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })

            .state('ad_check', {
                url: '/ad_check',
                data: {pageTitle: '广告检查'},
                templateUrl: 'templates/ad_check.html',
                controller: 'adCheckTaskController',
                cache : false,
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/adCheckTaskController.js',
                                'plugins/iosselect/iosSelect.css',
                                'plugins/iosselect/iscroll.js',
                                'plugins/iosselect/iosSelect.js',
                                'plugins/iosselect/iosMultiSelect.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })

            .state('check_task', {
                url: '/check_task',
                data: {pageTitle: '检查任务'},
                templateUrl: 'templates/check_task.html',
                controller: 'checkTaskController',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/checkTaskController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            .state('check_detail', {
                url: '/check_detail',
                cache : false,
                data: {pageTitle: '检查详情'},
                templateUrl: 'templates/check_detail.html',
                controller: 'checkDetailController',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/checkDetailController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            .state('bus', {
                url: '/bus',
                data: {pageTitle: '车辆信息'},
                templateUrl: 'templates/bus.html',
                controller: 'busCtrl',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/busController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            .state('stop', {
                url: '/stop',
                data: {pageTitle: '站点信息'},
                templateUrl: 'templates/stop.html',
                controller: 'stopCtrl',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/stopController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            .state('stopMapInfo', {
                url: '/stopMapInfo',
                data: {pageTitle: '站点定位信息'},
                templateUrl: 'templates/stopMapInfo.html',
                params: {transParams: {}},
                cache : false,
                controller: 'stopMapInfoCtrl',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/stopMapInfoController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            .state('busMapInfo', {
                url: '/busMapInfo',
                data: {pageTitle: '车辆定位信息'},
                params: {transParams: {}},
                cache : false,
                templateUrl: 'templates/busMapInfo.html',
                controller: 'busMapInfoCtrl',
                resolve: {
                    deps: ['$ocLazyLoad', function($ocLazyLoad) {
                        return $ocLazyLoad.load({
                            name: 'starter',
                            insertBefore: '#ng_load_plugins_before',
                            files: [
                                'js/controllers/busMapInfoController.js'
                            ],
                            cache:false
                        });
                    }]
                }
            })
            //.state('resCheck', {
            //    url: '/resCheck',
            //    data: {pageTitle: '资源检查'},
            //    templateUrl: 'templates/resCheck.html',
            //    controller: 'resCheckCtrl'
            //})
            //.state('resCheckDetail', {
            //    url: '/resCheckDetail',
            //    data: {pageTitle: '检查详情'},
            //    templateUrl: 'templates/resCheckDetail.html',
            //    params: {'resourceId': ''},
            //    cache : false,
            //    controller: 'resCheckDetailCtrl'
            //})
            //.state('adCheck', {
            //    url: '/adCheck',
            //    data: {pageTitle: '广告检查'},
            //    templateUrl: 'templates/adCheck.html',
            //    controller: 'adCheckCtrl'
            //})
            //.state('adCheckDetail', {
            //    url: '/adCheckDetail',
            //    data: {pageTitle: '检查详情'},
            //    templateUrl: 'templates/adCheckDetail.html',
            //    params: {transData: {}},
            //    cache : false,
            //    controller: 'adCheckDetailCtrl'
            //})
        ;

        // if none of the above states are matched, use this as the fallback
        // $urlRouterProvider.otherwise('/login');
        $urlRouterProvider.otherwise(function ($injector, $location) {
            if ($injector.get('$rootScope').user) {
                $location.path('/home');
            } else {
                $location.path('/bus');
            }
        });

    })

    .run(["$rootScope","localStore","$state",'settings','$location', '$ionicNavBarDelegate','$window','$ionicBackdrop', 'XCode',
                function ($rootScope,localStore, $state, settings,$location, $ionicNavBarDelegate,$window,$ionicBackdrop, XCode) {
            $ionicBackdrop.release();
            $rootScope.$state = $state; // state to be accessed from view
            $rootScope.$on('$stateChangeSuccess',function(event, toState, toParams, fromState, fromParams){
                //获取登录信息
                //window.webkit.messageHandlers.mobileAlert.postMessage({title:'success1321321',content:'1321321',action:false})

                $ionicNavBarDelegate.showBar(false);
                var $body = $('body');
                document.title = toState.data.pageTitle;
                var $iframe = $('<iframe></iframe>');
                $iframe.on('load', function () {
                    setTimeout(function () {
                        $iframe.off('load').remove();
                    }, 0);
                }).appendTo($body);
            });
            //window.webkit.messageHandlers.mobileAlert.postMessage({title:'提示',content:'登录超时11321!' + angular.toJson($location.search()),action:true})
            if($location.search().token != undefined && $location.search().token != ""
                && $location.search().userId != undefined && $location.search().userId != "") {
                localStore.set("token",$location.search().token);
                localStore.set("userId",$location.search().userId);
            }

            // 刷新时，如果不是登录页面，则获取用户信息
            if ($window.location.href.indexOf('#') > 0 && $window.location.href.indexOf('#/login') < 0 && $window.sessionStorage['user']) {
                $rootScope.userId = angular.fromJson($window.sessionStorage["user"]).id;
                $rootScope.token = angular.fromJson($window.sessionStorage["user"]).token;
                XCode.init();
            }
    }])

    //.directive('title', ['$rootScope', '$timeout',
    //    function($rootScope, $timeout) {
    //        return {
    //            restrict: 'AC',
    //            link: function() {
    //
    //                var listener = function(event, toState) {
    //                    console.log(toState);
    //                    $timeout(function() {
    //                        $rootScope.title = (toState.data && toState.data.pageTitle)
    //                            ? toState.data.pageTitle
    //                            : 'Default title';
    //                    });
    //                };
    //                $rootScope.$on('$stateChangeSuccess', listener);
    //            }
    //        };
    //    }
    //])

    // code表输出
    .filter('code', ['XCode', function(XCode) {

        return function(text, codeType) {
            if(text != undefined && codeType != undefined ) {
                return XCode.getName(codeType, text);
            }
        };
    }])

    .directive('hideTabs', function ($rootScope) {
        return {
            restrict: 'A',
            link: function (scope, element, attributes) {
                scope.$on('$ionicView.beforeEnter', function () {
                    scope.$watch(attributes.hideTabs, function (value) {
                        $rootScope.hideTabs = value;
                    });
                });

                scope.$on('$ionicView.beforeLeave', function () {
                    $rootScope.hideTabs = false;
                });
            }
        };
    })

    .directive('edDate', function ($rootScope, $cordovaDatePicker) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, element, attrs, ngModelController) {
                element.bind('click', function () {
                    $cordovaDatePicker.show({
                        date: new Date(),
                        mode: 'datetime',
                        androidTheme: 5
                    }).then(
                        function (date) {
                            var value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + " "
                                + (date.getHours() > 9 ? date.getHours() : '0' + date.getHours()) + ":" + (date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes());
                            element.text(value);
                            ngModelController.$setViewValue(value);
                            ngModelController.$modelValue = value;
                        }
                    );
                });
            }
        }
    })

    .directive('edIonInfiniteScroll', function () {
        return {
            restrict: 'A',
            template: ' ' +
            '     <div ng-if="!edit"  style="width: 100%;text-align: center;color: #555;"> <span>{{infiniteText}}</span></div>'
            + '<ion-infinite-scroll  immediate-check = "true" pulling-text="<span class=pulling-text - auto>{{pulltextchange1}}</span>" on-pulling="pulltext()"'
            + 'spinner="ripple" pulling-icon="ion-ios-refresh-empty"'
                +'ng-if="!edit && !moreData"  on-infinite="loadMoreData()" distance="5%" ></ion-infinite-scroll>',
            controller: function ($scope, $element, $ionicModal, Page, $ionicScrollDelegate) {
                $scope.$parent._pageSize = 0;
                $scope.$parent._pageIndex = 0;
                $scope.loadMoreData = function () {
                    console.log('上拉加载');
                    $scope.$parent._pageSize = $scope.$parent._pageSize + 5;
                    $scope.$parent.moreData = true;
                    $scope.$parent.init($scope.$parent._pageSize, $scope.$parent._pageIndex);
                    $scope.$broadcast('scroll.infiniteScrollComplete');
                    $scope.$parent.$broadcast('scroll.infiniteScrollComplete');
                }

            },
            link: function (scope, element, attrs, ngModelController) {

            }
        }
    })

    .directive('userSelect', function () {
        return {
            restrict: 'A',
            replace: false,
            transclude: true,
            require: 'ngModel',
            template: '<ion-item style="width: 102%;margin-right:0%;border:0px solid #fff"><div ng-repeat="i in items"><div ng-click="delete(i)" style="width: 49px;height:49px;background-color:#6BD8F7;border-radius: 100%;float: left;position:relative;top:3px;">'
            + '<p style="margin-top: 15px;text-align: center;width: 100%;height: 100%;color:#fff;">{{i.name}}</p></div><hr class="crossLine"></div>'
            + '<div style="float: left;"><a class="ion-plus-circled" style="font-size: 56px;color: #6BD8F7;"  ng-click="show()"></a></div></ion-item>',
            controller: function ($scope, $element, $ionicModal, Page) {
                $scope.items = [];
                $ionicModal.fromTemplateUrl('templates/userSelect.html', {
                    scope: $scope
                }).then(function (modal) {
                    $scope.modal = modal;
                });

                $scope.show = function () {
                    $scope.init();
                    $scope.modal.show();
                }
                $scope.closeLogin = function () {
                    $scope.modal.hide();
                }
                $scope.showModal = function (obj) {
                    if (obj.type == "user") {
                        $element.find('input').val(obj.name);
                        $scope.selectUser = obj;
                        $scope.update(obj);
                        $scope.closeLogin();
                        return;
                    }
                    var datas = [];
                    for (var i = 0; i < $scope.rows.length; i++) {

                        if ($scope.rows[i].pId == obj.id) {
                            if (obj.id == '0') {
                                if ($scope.rows[i].id.indexOf('-') != -1) {
                                    $scope.rows[i].id = $scope.rows[i].id.split('-')[1];
                                    datas.push($scope.rows[i]);
                                }
                            } else {
                                datas.push($scope.rows[i]);
                            }

                        }
                    }
                    if (datas.length > 0) {
                        $scope.datas = datas;
                        for (var i = 0; i < $scope.datas.length; i++) {
                            var childrens = 0;
                            if ($scope.datas[i].type == "user") {
                                continue;
                            }
                            for (var j = 0; j < $scope.rows.length; j++) {
                                if ($scope.rows[j].pId == $scope.datas[i].id) {
                                    childrens++;
                                }
                            }
                            $scope.datas[i].childrens = childrens;
                        }
                    }
                }

                $scope.back = function () {
                    if ($scope.datas.length > 0) {
                        var obj = $scope.retParent($scope.datas[0]);
                        if (obj == null) {
                            $scope.modal.hide();
                            return;
                        }
                        $scope.showModal({id: obj.pId});
                    } else {
                        $scope.modal.hide();
                    }
                }

                $scope.retParent = function (obj) {
                    if (obj == null) {
                        return {};
                    }
                    if ($scope.rows.length > 0) {
                        for (var i = 0; i < $scope.rows.length; i++) {
                            if ($scope.rows[i].id == obj.pId) {
                                return $scope.rows[i];
                            }
                        }
                    } else {
                        return {};
                    }
                }

                $scope.delete = function (obj) {
                    if ($scope.items != null) {
                        for (var i = 0; i < $scope.items.length; i++) {
                            if ($scope.items[i].id == obj.id) {
                                $scope.items.splice(i, 1);
                                break;
                            }
                        }
                        $scope.update();
                    }
                }

                $scope.init = function () {
                    Page.ajaxPost('user/tree.do', null, function (resp) {
                        var obj = {id: "dept-0"};
                        $scope.rows = resp.data.org;
                        console.log($scope.rows);
                        $scope.showModal(obj);
                    });
                }
            },
            link: function (scope, element, attrs, ngModelController) {

                scope.update = function (obj) {
                    if (obj == null) {
                        var userIds = "";
                        for (var i = 0; i < scope.items.length; i++) {
                            if (i == scope.items.length - 1) {
                                userIds += scope.items[i].id
                                continue;
                            }
                            userIds += scope.items[i].id + ",";
                        }
                        ngModelController.$setViewValue(userIds);
                        ngModelController.$render();
                        return;
                    }
                    if (attrs.edMultiple == 'true') {
                        scope.delete(obj);
                        scope.items[scope.items.length] = obj;
                        var userIds = "";
                        for (var i = 0; i < scope.items.length; i++) {
                            if (i == scope.items.length - 1) {
                                userIds += scope.items[i].id
                                continue;
                            }
                            userIds += scope.items[i].id + ",";
                        }
                        ngModelController.$setViewValue(userIds);
                        ngModelController.$render();
                    } else {
                        scope.items[0] = obj;
                        ngModelController.$setViewValue(obj.id);

                    }
                }


            }
        }
    })

    .directive('edOptions', function ($rootScope, Page, XCode,ApiEndpoint) {
        return {
            restrict: 'A',
            controller: function ($rootScope, $scope, $element, Page) {

            },
            link: function (scope, element, attributes) {
                if (!$rootScope.options) {
                    XCode.init();
                }
                var str = element.text();
                var model = str.substring(2, str.length - 2);
                var codeType = attributes.edOptions;
                if (model.indexOf(".") != -1) {
                    var value = scope[model.split('.')[0]][model.split('.')[1]];
                } else {
                    var value = scope[codeType];
                }
                if (codeType == 'user') {
                    Page.ajaxPost(ApiEndpoint.queryUserUrl, {userId: value}, function (resp) {
                        element.text(resp.data.name);
                    });
                } else {
                    element.text(XCode.getName(codeType, value))
                }

            }
        };
    })

    .directive('zlhFocus', function($timeout, $parse) {
        return {
            link: function(scope, element, attrs) {
                var model = $parse(attrs.zlhFocus);
                scope.$watch(model, function(value) {
                    if(value === true) {
                        $timeout(function() {
                            $(element[0]).focus().trigger("click");
                        },300);
                    }
                });
                element.bind('blur', function() {
                    scope.$apply(model.assign(scope, false));
                });
            }
        };
    })


    .directive('edUserDept', ['Page', function (Page) {
        return {

            restrict: 'A',
            scope: true,
            require: 'ngModel',

            controller: ['$scope', '$element', function ($scope, $element) {
            }],

            link: function (scope, elem, attrs, ngModelController) {
                scope.$watch(attrs.edUserDept, function (newValue, oldValue) {
                    if (newValue != oldValue
                        || (newValue && newValue == oldValue && (elem.children().length == 0 || (elem.children().length == 1 && elem.children()[0].text == '')))) {
                        Page.ajaxGet('department/ofUser.do', {userId: newValue}, function (resp) {
                            var options = '';
                            $(resp.data).each(function (index, dept) {
                                if (index == 0) {
                                    ngModelController.$setViewValue(dept.deptId);// 只包含id
                                    ngModelController.$render();
                                }
                                options += '<option value="' + dept.deptId + '">' + dept.deptName + '</option>';
                            });
                            $(elem).html(options);
                        });
                    }
                });
            }

        };
    }])

;

